/**
 * Author : Fengyuan(Franklin) Zhang
 * Date : 2018/12/28
 * Description : File operation
 */

var fs = require('fs');
var crypto = require('crypto');

var FileOpera = function () {
};

module.exports = FileOpera;

//! Build a directory
FileOpera.buildDir = function (path, callback) {
    fs.access(path, function (err) {
        if (err) {
            // console.log('fail in 1 : ' + path);
            fs.mkdir(path, function (err, result) {
                if(err){
                    // console.log('fail in 2');
                }
                return callback();
            });
        }
        else {
            callback();
        }
    });
};

//! Delete a directory(or file)
FileOpera.rmdir = function (path) {
    if (!fs.existsSync(path)) {
        return true;
    }
    var stat = fs.statSync(path);
    if (stat.isFile()) {
        fs.unlinkSync(path);
        return true;
    }
    else if (stat.isDirectory()) {
        path += '/';
        var files = fs.readdirSync(path);
        for (var i = 0; i < files.length; i++) {
            FileOpera.rmdir(path + files[i]);
        }
        fs.rmdirSync(path);
    }
};

//! Copy
FileOpera.copy = function (source, target, callback) {
    fs.readFile(source, function (err, data) {
        if (err) {
            return callback(err);
        }
        fs.writeFile(target, data, function (err, result) {
            if (err) {
                return callback(err);
            }
            return callback(null, result);
        });
    });
}

//! Get MD5
FileOpera.getMD5 = function (fpath, callback) {
    if (!fs.existsSync(fpath)) {
        return callback(new Error('can not find file!'));
    }
    var md5sum = crypto.createHash('md5');
    var stream = fs.createReadStream(fpath);
    stream.on('data', function (chunk) {
        md5sum.update(chunk);
    });
    stream.on('end', function () {
        str = md5sum.digest('hex');
        return callback(null, str);
    });
};